package com.chinackts.exceptionadvice.support.dingding;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * Created by sunqian on 2017/3/8.
 */
public class SendDing {

    private static final Logger LOGGER = LoggerFactory.getLogger(SendDing.class);

    private final OkHttpClient okHttpClient;
    private final String url;
    private final String secret;

    public SendDing(OkHttpClient okHttpClient, String url, String secret) {
        this.okHttpClient = okHttpClient;
        this.url = url;
        this.secret = secret;
    }

    public void send(JSONObject content) {
        Long timestamp = System.currentTimeMillis();
        String sign;
        try {
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(String.format("秘钥加签失败，原因：%s", e.getMessage()));
        }
        String timestamp_sign = "&timestamp=" + timestamp + "&sign=" + sign;

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), content.toString());
        Request request = new Request.Builder()
                .url(url + timestamp_sign)
                .post(requestBody)
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                LOGGER.info("发送钉钉消息成功");
            }
        } catch (Exception e) {
            LOGGER.error("发送钉钉消息失败: {}", ExceptionUtils.getStackTrace(e));
        }
    }
}
